package com.example.aacwebdemo.netty.a;

import com.example.aacwebdemo.netty.b.SSLConfig;
import com.example.aacwebdemo.netty.b.SSLContextFactory;
import com.example.aacwebdemo.netty.b.SslCheckServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslHandler;

/**
 * @author zhao.xin06679
 * @date 2021年06月29日 17:57
 */
public class HttpsServer {

    public static void start(final int port) throws Exception {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .group(boss, worker)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            SSLConfig sslConfig = new SSLConfig();
                            sslConfig.isSSL(true);

                            sslConfig.pkPath("C:\\jks\\test.jks");
                            sslConfig.passwd("hsc123");

//                            SslHandler sslHandler = SSLContextFactory.getOpenSslHandler(
//                                    sslConfig, ch.alloc());
                            SslHandler sslHandler =SSLContextFactory.getSslHandler(sslConfig);


                            if (sslHandler != null) {
                                System.out.println("sslHandler is not null");
                                ch.pipeline().addLast("ssl", sslHandler);
                                //添加一个提示成功的类
                                ch.pipeline().addLast(new SslCheckServerHandler());
                            }else{
                                System.out.println("sslHandler is null");
                            }

                            ch.pipeline().addLast("http-decoder", new HttpServerCodec());
                            ch.pipeline().addLast(new HttpsSeverHandler());

                        }
                    });
            System.out.println("start: 7777");
            ChannelFuture future = serverBootstrap.bind(port).sync();
            future.channel().closeFuture().sync();

        } catch (Exception e){
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {

        start(7777);
    }




}
